use super::*;

pub struct Parallel {
    finished: bool,
    children: Vec<Box<dyn ITask>>,
}

impl Parallel {
    pub fn new<It>(children: It) -> Box<Self> where It: IntoIterator<Item = Box<dyn ITask>> {
        Box::new(Self {
            finished: false,
            children: children.into_iter().collect(),
        })
    }

    pub fn add_child(&mut self, child: Box<dyn ITask>) {
        self.children.push(child);
    }
}

impl ITask for Parallel {
    fn step(&mut self) {
        self.finished = self.children.iter_mut().all(|child| 
            if !child.is_finished() {
                child.step();
                false
            } else {
                true
            }
        );
    }

    fn reset(&mut self) {
        self.finished = false;
        for task in self.children.iter_mut() {
            task.reset();
        }
    }

    fn is_finished(&self) -> bool {
        self.finished
    }
}
